package com.crm.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crm.common.constant.HttpStatus;
import com.crm.common.page.TableDataInfo;
import com.crm.common.result.AjaxResult;
import com.crm.common.utils.UserThreadLocal;
import com.crm.domain.Business;
import com.crm.domain.BusinessRecord;
import com.crm.dto.BusinessAddDto;
import com.crm.dto.BusinessListDto;
import com.crm.service.BusinessRecordService;
import com.crm.service.BusinessService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商机Controller
 */
@RestController
@RequestMapping("/business")
@RequiredArgsConstructor
public class BusinessController {
    @Autowired
    private BusinessService businessService;

    private final BusinessRecordService businessRecordService;

    /**
     * 查询商机列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BusinessListDto dto){
        return businessService.list(dto);
    }

    /**
     * 查询公海池
     */
    @GetMapping("/pool")
    public TableDataInfo pool(BusinessListDto dto){
        return businessService.pool(dto);
    }
    
    /**
     * 获取商机详情信息
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id){
        Business business = businessService.getInfo(id);
        AjaxResult ajax = new AjaxResult();
        ajax.put("data", business);
        return ajax;
    }

    /**
     * 删除商机
     * @param ids 商机ID数组
     * @return 结果
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids){
        boolean result = businessService.remove(ids);
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", result ? 200 : 500);
        ajax.put("msg", result ? "删除成功" : "删除失败");
        return ajax;
    }
    
    /**
     * 新增商机
     */
    @PostMapping
    public AjaxResult add(@RequestBody Business business) {

        return businessService.addBusiness(business);
    }
    
    /**
     * 新增商机（使用DTO）
     */
    @PostMapping("/add")
    public AjaxResult addWithDto(@RequestBody BusinessAddDto dto) {
        return businessService.addBusiness(dto);
    }
    
    /**
     * 修改商机
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Business business) {
        boolean result = businessService.updateById(business);
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", result ? 200 : 500);
        ajax.put("msg", result ? "修改成功" : "修改失败");
        return ajax;
    }
    
    /**
     * 根据客户ID查询关联的商机列表
     */
    @GetMapping("/customer/{customerId}")
    public AjaxResult listByCustomerId(@PathVariable Long customerId) {
        LambdaQueryWrapper<Business> queryWrapper = Wrappers.<Business>lambdaQuery()
                .eq(Business::getCustomerId, customerId)
                .eq(Business::getDelFlag, 0);
                
        List<Business> list = businessService.list(queryWrapper);
        
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", 200);
        ajax.put("data", list);
        return ajax;
    }
    
    /**
     * 商机放入公海池
     */
    @PutMapping("/pool/{id}")
    public AjaxResult moveToPool(@PathVariable Long id) {
        Business business = businessService.getById(id);
        if (business == null) {
            AjaxResult ajax = new AjaxResult();
            ajax.put("code", 500);
            ajax.put("msg", "商机不存在");
            return ajax;
        }
        
        business.setIsPool(1);
        boolean result = businessService.updateById(business);
        
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", result ? 200 : 500);
        ajax.put("msg", result ? "操作成功" : "操作失败");
        return ajax;
    }
    
    /**
     * 认领公海池商机
     */
    @PutMapping("/claim/{id}")
    public AjaxResult claimFromPool(@PathVariable Long id) {
        Business business = businessService.getById(id);
        if (business == null) {
            AjaxResult ajax = new AjaxResult();
            ajax.put("code", 500);
            ajax.put("msg", "商机不存在");
            return ajax;
        }
        
        if (business.getIsPool() != 1) {
            AjaxResult ajax = new AjaxResult();
            ajax.put("code", 500);
            ajax.put("msg", "该商机不在公海池中");
            return ajax;
        }
        
        business.setIsPool(0);
        business.setUpdateBy("admin"); // 这里应该从登录用户中获取
        business.setUpdateTime(LocalDateTime.now());
        
        boolean result = businessService.updateById(business);
        
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", result ? 200 : 500);
        ajax.put("msg", result ? "认领成功" : "认领失败");
        return ajax;
    }

    @GetMapping("/record/list")
    public AjaxResult listRecord(Long businessId){
        List<BusinessRecord> businessRecords = businessRecordService.list(Wrappers.<BusinessRecord>lambdaQuery().eq(BusinessRecord::getBusinessId, businessId));
        AjaxResult ajax = new AjaxResult();
        ajax.put("rows", businessRecords);
        ajax.put("total", businessRecords.size());
        ajax.put("code", HttpStatus.SUCCESS);
        return ajax;
    }
}
